<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>business_add</title>
    <link rel="stylesheet" href="../../../static/layer/css/layui.css" media="all"/>
    <style>
        .view-form .layui-input-block, .view-form .layui-input-inline {
            line-height: 36px;
            background: #eeeeee;
            padding: 0 20px;
            font-size: 16px;
        }

        .view-form .layui-input-block-all {
            padding: 0;
        }

        .unit-list span, .floor-list span {
            position: absolute;
            right: 20px;
        }

        .unit-list .on-color-green, .floor-list .on-color-green {
            color: #5FB878;
        }

        .unit-list .off-color-red, .floor-list .off-color-red {
            color: #FF5722;
        }

        .layui-btn-mini {
            margin-top: 9px;
        }

        .unit-list .layui-btn-mini, .floor-list .layui-btn-mini {
            position: absolute;
            right: 20px;
        }

        .unit-list .layui-input-inline50, .floor-list .layui-input-inline50 {
            width: 50px !important;
            position: absolute;
            right: 80px;
        }

        .edit-building {
            display: none;
        }

        .layui-form-label {
            width: 100px;
        }
        .layui-input-block {
            margin-left: 130px;
        }
        #allmap {
            width:100%;
            height:500px;
            margin-top: 10px;
        }
    </style>

    <!-- 百度地图 -->
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=VoGWsEzA2kr5G981Lt3EgNUhREBz4KsW"></script>
</head>

<body>
<div style="padding: 20px;">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">楼宇名称：</label>
            <div class="layui-input-block">
                <input type="text" name="BUILDING_NAME" lay-verify="required" placeholder="请输入楼宇名称" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <!--<label class="layui-form-label">楼宇面积(m²)：</label>
            <div class="layui-input-inline">
                <input type="number" name="BUILDING_AREA" lay-verify="required" placeholder="请输入楼宇面积" autocomplete="off"
                       class="layui-input">
            </div>-->
            <label class="layui-form-label">楼宇高度(m)：</label>
            <div class="layui-input-inline">
                <input type="number" name="BUILDING_HIGH" lay-verify="required" placeholder="请输入楼宇高度"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">楼宇单元：</label>
            <div class="layui-input-block edit-building">
                <a class="layui-btn layui-btn-mini" href="javascript:createUnit();"><i class="layui-icon"></i> 新增单元</a>
            </div>
            <div class="unit-list">
                <div class="layui-input-inline">
                    <select name="unitStart">
                    </select>
                </div>
                <div class="layui-form-mid"> 至</div>
                <div class="layui-input-inline">
                    <select name="unitEnd">
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item all-floor-list">
            <label class="layui-form-label">楼宇楼层：</label>
            <div class="layui-input-block layui-input-block-all">
                <select name="selectUnit" lay-filter="selectUnit">
                </select>
            </div>
            <div class="layui-input-block edit-building">
                <a class="layui-btn layui-btn-mini" href="javascript:createFloor();"><i class="layui-icon"></i>
                    新增楼层</a>
            </div>
            <div class="floor-list">
                <div class="layui-input-inline">
                    <select name="floorStart">
                    </select>
                </div>
                <div class="layui-form-mid"> 至</div>
                <div class="layui-input-inline">
                    <select name="floorEnd">
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">楼宇位置：</label>
            <div class="layui-input-block">
                <input type="text" id="suggestId" name="BUILDING_ADDRESS" lay-verify="required" placeholder="请输入楼宇位置"
                       autocomplete="off" class="layui-input">
            </div>
            <div class="layui-input-block">
                <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                <div id="allmap"></div>
            </div>
        </div>
        <div style="display: none;" class="layui-form-item">
            <label class="layui-form-label">位置经度：</label>
            <div class="layui-input-inline">
                <input type="number" id="lng" name="BUILDING_LNG" lay-verify="" placeholder="请输入位置经度" autocomplete="off"
                       class="layui-input">
            </div>
            <label class="layui-form-label">位置纬度：</label>
            <div class="layui-input-inline">
                <input type="number" id="lat" name="BUILDING_LAT" lay-verify="" placeholder="请输入位置纬度" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">楼宇图片：</label>
            <div class="layui-input-block layui-upload">
                <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多图片</button>
                <div class="layui-upload-list">
                    <table class="layui-table">
                        <thead>
                        <tr>
                            <th>缩略图</th>
                            <th>文件名</th>
                            <th>大小</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="demoList"></tbody>
                    </table>
                </div>
                <button type="button" class="layui-btn" id="testListAction">开始上传</button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用：</label>
            <div class="layui-input-block">
                <input type="checkbox" checked="" name="IS_OPEN" lay-skin="switch" lay-filter="switchTest"
                       lay-text="启用|关闭">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注信息：</label>
            <div class="layui-input-block">
                <textarea name="BUILDING_INFO" placeholder="请输入备注信息" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item operate-button-group">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="business">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript" src="../../../static/js/common/queryUtils.js"></script>
<script type="text/javascript" src="../../../static/layer/layui.js"></script>
<script type="text/javascript" src="../../../static/ujs/admin/map.js"></script>
<script>
    var uploadfiles = new Array(); // 要上传的文件列表路径
    var $;
    var form;
    layui.use(['jquery', 'form', 'layer', 'upload'], function () {
        $ = layui.jquery;
        form = layui.form;
        var upload = layui.upload;
        var layer = layui.layer;

        //多文件列表示例
        var files;
        var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#testList'
            , url: '/servlet/UploadHandleServlet'
            // ,accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#testListAction'
            , choose: function (obj) {
                files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td><img src="' + result + '" alt="' + file.name + '" class="layui-upload-img"></td>'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                        return false;
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                    });

                    demoListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.errcode == 0) { //上传成功
                    var obj = {};
                    obj.name = res.data.fileName;
                    obj.size = res.data.fileSize;
                    obj.ext = res.data.extName;
                    obj.url = res.data.fileUrl;
                    uploadfiles.push(obj);
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(4).html(''); //清空操作
                    delete files[index]; //删除文件队列已经上传成功的文件
                    return;
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(3).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

        $("select[name='unitStart']").empty();
        $("select[name='unitEnd']").empty();
        $("select[name='floorStart']").empty();
        $("select[name='floorEnd']").empty();
        for (var i = 1; i < 11; i++) {
            var str = '<option value="' + i + '">' + i + ' 单元</option>';
            $("select[name='unitStart']").append(str);
            $("select[name='unitEnd']").append(str);
        }
        for (var i = 1; i > -6; i--) {
            var str = '<option value="' + i + '">' + i + ' 层</option>';
            if (i !== 0) {
                $("select[name='floorStart']").append(str);
            }
        }
        for (var i = 1; i < 101; i++) {
            var str = '<option value="' + i + '">' + i + ' 层</option>';
            $("select[name='floorEnd']").append(str);
        }
        form.render("select");

        //操作类型：add新增，edit修改，view查看
        var operateType = QueryUtils.GetQueryString("type");
        var id = QueryUtils.GetQueryString("id");
        var businessId = QueryUtils.GetQueryString("businessId");
        switch (operateType) {
            case "add":
                $(".layui-input-block-all").remove();
                break;
            case "edit":
                $.ajax({
                    url: "/building/info",
                    data: {BUILDING_ID: id},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {

                            // 初始化附件
                            var attachments = res.attachmentData;
                            if (!!attachments) {
                                var host = location.host;
                                for (var i = 0; i < attachments.length; i++) {
                                    var attachment = attachments[i];
                                    var demoListView = $('#demoList');
                                    var tr = $(['<tr id="upload-' + (i + 1) + '">'
                                        , '<td><img src="http://' + host + '/' + attachment.PATH + '" alt="' + attachment.NAME + '" class="layui-upload-img"></td>'
                                        , '<td>' + attachment.NAME + '</td>'
                                        , '<td>' + (attachment.SIZE / 1014).toFixed(1) + 'kb</td>'
                                        , '<td><span style="color: #5FB878;">上传成功</span></td>'
                                        , '<td>'
                                        , '<a onclick=\'operate.deleteImg(this, "' + attachment.ID + '");\' class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</a>'
                                        , '</td>'
                                        , '</tr>'].join(''));
                                    demoListView.append(tr);

                                    var obj = {};
                                    obj.id = attachment.ID;
                                    obj.name = attachment.NAME;
                                    obj.size = attachment.SIZE;
                                    obj.ext = attachment.EXT;
                                    obj.url = attachment.PATH;
                                    uploadfiles.push(obj);
                                }
                            }

                            $("input[name='BUILDING_NAME']").val(res.data.BUILDING_NAME);
                            $("input[name='BUILDING_AREA']").val(res.data.BUILDING_AREA);
                            $("input[name='BUILDING_HIGH']").val(res.data.BUILDING_HIGH);
                            $("input[name='BUILDING_ADDRESS']").val(res.data.BUILDING_ADDRESS);
                            $("input[name='BUILDING_LNG']").val(res.data.BUILDING_LNG);
                            $("input[name='BUILDING_LAT']").val(res.data.BUILDING_LAT);
                            setPlaceEdit(res.data.BUILDING_LNG, res.data.BUILDING_LAT);

                            var unitList = res.unitList;
                            $(".unit-list").empty();
                            $(".floor-list").empty();
                            $(".edit-building").show();
                            if (unitList.length > 0) {
                                for (var i = 0; i < unitList.length; i++) {
                                    var flag;
                                    var flag1;
                                    if (unitList[i].IS_OPEN === "on") {
                                        flag = 'checked=""';
                                        flag1 = '已';
                                    } else if (unitList[i].IS_OPEN === "off") {
                                        flag = "";
                                        flag1 = "未";
                                    }
                                    var str = '<div class="layui-input-block unit-list-res" data-id="' + unitList[i].UNIT_ID + '" data-name="' + unitList[i].UNIT_NAME + '" data-open="' + unitList[i].IS_OPEN + '" data-deleted="0">' +
                                        '          <div class="layui-form-mid layui-word-aux">' + unitList[i].UNIT_NAME + ' 单元</div>\n' +
                                        '                <div class="layui-input-inline layui-input-inline50">\n' +
                                        '                    <input type="checkbox" ' + flag + ' name="UNIT_IS_OPEN" data-unitid="' + unitList[i].UNIT_ID + '" lay-skin="switch" lay-filter="switchUnit"\n' +
                                        '                        lay-text="启用|关闭">\n' +
                                        '                </div>\n' +
                                        '                <a class="layui-btn layui-btn-primary layui-btn-mini" href="javascript:;" onclick="deleteUnit(this);" ><i class="layui-icon"></i> 删除</a>' +
                                        '</div>';
                                    $(".unit-list").append(str);
                                    var sstr = '<option value="' + unitList[i].UNIT_ID + '">' + unitList[i].UNIT_NAME + '单元 [' + flag1 + '开启]</option>';
                                    $("select[name='selectUnit']").append(sstr);
                                }
                            }

                            getFloorByUnitId(unitList[0].UNIT_ID, "edit");

                            if (res.data.IS_OPEN === "on") {
                                $("input[name='IS_OPEN']").parent().html('<input type="checkbox" checked="" name="IS_OPEN" lay-skin="switch" lay-filter="switchTest" lay-text="启用|关闭">');
                            } else if (res.data.IS_OPEN === "off") {
                                $("input[name='IS_OPEN']").parent().html('<input type="checkbox" name="IS_OPEN" lay-skin="switch" lay-filter="switchTest" lay-text="启用|关闭">');
                            }
                            $("textarea[name='BUILDING_INFO']").val(res.data.BUILDING_INFO);
                            form.render();
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
                break;
            case "view":
                $.ajax({
                    url: "/building/info",
                    data: {BUILDING_ID: id},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {
                            $("#testList").remove();
                            $("#testListAction").remove();
                            // 初始化附件
                            var attachments = res.attachmentData;
                            if (!!attachments) {
                                var host = location.host;
                                for (var i = 0; i < attachments.length; i++) {
                                    var attachment = attachments[i];
                                    var demoListView = $('#demoList');
                                    var tr = $(['<tr id="upload-' + (i + 1) + '">'
                                        , '<td><img src="http://' + host + '/' + attachment.PATH + '" alt="' + attachment.NAME + '" class="layui-upload-img"></td>'
                                        , '<td>' + attachment.NAME + '</td>'
                                        , '<td>' + (attachment.SIZE / 1014).toFixed(1) + 'kb</td>'
                                        , '<td><span style="color: #5FB878;"></span></td>'
                                        , '<td>'
                                        , '</td>'
                                        , '</tr>'].join(''));
                                    demoListView.append(tr);

                                    var obj = {};
                                    obj.name = attachment.NAME;
                                    obj.size = attachment.SIZE;
                                    obj.ext = attachment.EXT;
                                    obj.url = attachment.PATH;
                                    uploadfiles.push(obj);
                                }
                            }

                            $(".layui-form").addClass("view-form");
                            $("input[name='BUILDING_NAME']").parent().html(res.data.BUILDING_NAME);
                            $("input[name='BUILDING_AREA']").parent().html(res.data.BUILDING_AREA);
                            $("input[name='BUILDING_HIGH']").parent().html(res.data.BUILDING_HIGH);
                            $("input[name='BUILDING_ADDRESS']").parent().html(res.data.BUILDING_ADDRESS);
                            $("input[name='BUILDING_LNG']").parent().html(res.data.BUILDING_LNG);
                            $("input[name='BUILDING_LAT']").parent().html(res.data.BUILDING_LAT);
                            setPlaceEdit(res.data.BUILDING_LNG, res.data.BUILDING_LAT);

                            var unitList = res.unitList;
                            $(".unit-list").empty();
                            $(".floor-list").empty();
                            $("select[name='selectUnit']").empty();
                            if (unitList.length > 0) {
                                getFloorByUnitId(unitList[0].UNIT_ID, "view");
                                for (var i = 0; i < unitList.length; i++) {
                                    var flag;
                                    var color;
                                    if (unitList[i].IS_OPEN === "on") {
                                        flag = "已";
                                        color = "on-color-green";
                                    } else if (unitList[i].IS_OPEN === "off") {
                                        flag = "未";
                                        color = "off-color-red";
                                    }
                                    var str = '<div class="layui-input-block">\n' +
                                        unitList[i].UNIT_NAME + ' 单元 <span class="' + color + '">' + flag + '开启</span>' +
                                        '      </div>';
                                    $(".unit-list").append(str);
                                    var sstr = '<option value="' + unitList[i].UNIT_ID + '">' + unitList[i].UNIT_NAME + '单元 [' + flag + '开启]</option>';
                                    $("select[name='selectUnit']").append(sstr);
                                }
                            }

                            form.render("select");

                            if (res.data.IS_OPEN === "on") {
                                $("input[name='IS_OPEN']").parent().html("开启");
                            } else if (res.data.IS_OPEN === "off") {
                                $("input[name='IS_OPEN']").parent().html("关闭");
                            }
                            $("textarea[name='BUILDING_INFO']").parent().html(res.data.BUILDING_INFO);
                            $(".operate-button-group").remove();
                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
                break;
        }

        function getFloorByUnitId(uid, type) {
            if (type === "view"){
                $.ajax({
                    url: "/building/floorInfo",
                    data: {UNIT_ID: uid},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {

                            var floorList = res.data;

                            $(".floor-list").empty();
                            if (floorList.length > 0) {
                                    for (var i = floorList.length - 1; i >= 0; i--) {
                                        var flag;
                                        var color;
                                        if (floorList[i].IS_OPEN === "on") {
                                            flag = "已";
                                            color = "on-color-green";
                                        } else if (floorList[i].IS_OPEN === "off") {
                                            flag = "未";
                                            color = "off-color-red";
                                        }
                                        var str = '<div class="layui-input-block">\n' +
                                            floorList[i].FLOOR_NAME + ' 层 <span class="' + color + '">' + flag + '开启</span>' +
                                            '      </div>';
                                        $(".floor-list").append(str);
                                    }
                                }

                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            } else if (type === "edit"){
                $.ajax({
                    url: "/building/info",
                    data: {BUILDING_ID: id},
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "0") {

                            var floorList = res.floorList;

                            $(".all-floor-list").find(".floor-list").remove();

                            if (floorList.length > 0){
                                var floorChildList;
                                for (var j = 0; j < floorList.length; j++){
                                    var s = '<div class="floor-list" data-id="'+floorList[j].UNIT_ID+'" style="display: none;"></div>';
                                    $(".all-floor-list").append(s);
                                    floorChildList = floorList[j].floorList;
                                    for (var i = floorChildList.length - 1; i >= 0; i--) {
                                        var flag;
                                        if (floorChildList[i].IS_OPEN === "on") {
                                            flag = 'checked=""';
                                        } else if (floorChildList[i].IS_OPEN === "off") {
                                            flag = "";
                                        }
                                        var str = '<div class="layui-input-block floor-list-res" data-id="' + floorChildList[i].FLOOR_ID + '" data-name="' + floorChildList[i].FLOOR_NAME + '" data-open="' + floorChildList[i].IS_OPEN + '" data-deleted="0">' +
                                            '          <div class="layui-form-mid layui-word-aux">' + floorChildList[i].FLOOR_NAME + ' 层</div>\n' +
                                            '                <div class="layui-input-inline layui-input-inline50">\n' +
                                            '                    <input type="checkbox" ' + flag + ' name="FLOOR_IS_OPEN" data-unitid="' + floorChildList[i].FLOOR_ID + '" lay-skin="switch" lay-filter="switchFloor"\n' +
                                            '                        lay-text="启用|关闭">\n' +
                                            '                </div>\n' +
                                            '                <a class="layui-btn layui-btn-primary layui-btn-mini" href="javascript:;" onclick="deleteFloor(this);" ><i class="layui-icon"></i> 删除</a>' +
                                            '</div>';
                                        $(".floor-list").eq(j).append(str);
                                    }
                                }
                            }

                            form.render();

                            $(".floor-list").each(function (index, elem) {
                                if ($(this).data("id") === $("select[name='selectUnit']").val()) {
                                    $(this).show();
                                }
                            });

                        } else if (res.errcode === "1") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            }
        }


        //监听指定开关
        form.on('switch(switchUnit)', function (data) {
            if (this.checked === true) {
                layer.tips('温馨提示：已启用' + '', data.othis);
                data.othis.parent().parent().attr("data-open", "on");
            } else if (this.checked === false) {
                layer.tips('温馨提示：已关闭' + '', data.othis);
                data.othis.parent().parent().attr("data-open", "off");
            }
        });

        //监听指定开关
        form.on('switch(switchFloor)', function (data) {
            if (this.checked === true) {
                layer.tips('温馨提示：已启用' + '', data.othis);
                data.othis.parent().parent().attr("data-open", "on");
            } else if (this.checked === false) {
                layer.tips('温馨提示：已关闭' + '', data.othis);
                data.othis.parent().parent().attr("data-open", "off");
            }
        });

        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            if (this.checked === true) {
                layer.tips('温馨提示：保存成功后楼宇立即启用' + '', data.othis);
            } else if (this.checked === false) {
                layer.tips('温馨提示：保存成功后楼宇需开启后可用' + '', data.othis);
            }
        });

        //监听指定下拉框
        form.on('select(selectUnit)', function (data) {
            getFloorByUnitId(data.value, operateType);
        });

        //监听提交
        form.on('submit(business)', function (data) {
            /*layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            });*/
            if (!data.field.IS_OPEN) {
                data.field.IS_OPEN = "off"; //如果是否开启为未开启则设置为off
            }
            if (operateType === "add") {
                data.field.BUSINESS_ID = businessId;
                var sdata = {};
                sdata.BUILDING = data.field;
                sdata.ATTACHMENT = uploadfiles;
                var sendData = {};
                sendData.DATA = JSON.stringify(sdata);

                layer.msg('确认保存楼宇吗', {
                    time: 0
                    , btn: ['确定', '取消']
                    , shade: 0.3
                    , yes: function (index) {
                        layer.close(index); // 关闭当前提示框
                        $.ajax({
                            url: "/building/save",
                            data: sendData,
                            dataType: "json",
                            type: "post",
                            async: false,
                            success: function (res) {
                                if (res.errcode === "0") {
                                    var i = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(i);  // 关闭新建楼宇页面
                                    parent.reload();    // 父页面表格刷新
                                    parent.layer.msg("保存成功", {offset: '150px'});   // 父页面弹出保存成功
                                } else if (res.errcode === "1") {
                                    layer.msg(res.errmsg, function () {
                                    });
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                console.error(XMLHttpRequest.status);
                                console.error(XMLHttpRequest.readyState);
                                console.error(textStatus);
                            }
                        });
                    }
                });
            } else if (operateType === "edit") {
                data.field.BUSINESS_ID = businessId;
                data.field.BUILDING_ID = id;

                var unitList = new Array();
                for (var i = 0; i < $(".unit-list").find(".unit-list-res").length; i++) {
                    var unitRes = {};
                    var elem = $(".unit-list").find(".unit-list-res")[i];
                    unitRes.UNIT_ID = $(elem).data("id");
                    unitRes.UNIT_NAME = $(elem).data("name");
                    unitRes.IS_OPEN = $(elem).data("open");
                    unitRes.IS_DELETED = $(elem).data("deleted");
                    unitList.push(unitRes);
                }

                var floorList = new Array();
                for (var i = 0; i < $(".floor-list").find(".floor-list-res").length; i++) {
                    var floorRes = {};
                    var elem = $(".floor-list").find(".floor-list-res")[i];
                    floorRes.FLOOR_ID = $(elem).data("id");
                    floorRes.UNIT_ID = $(elem).parent().data("id");
                    floorRes.FLOOR_NAME = $(elem).data("name");
                    floorRes.IS_OPEN = $(elem).data("open");
                    floorRes.IS_DELETED = $(elem).data("deleted");
                    floorList.push(floorRes);
                }

                data.field.unitList = JSON.stringify(unitList);
                data.field.floorList = JSON.stringify(floorList);

                var sdata = {};
                sdata.BUILDING = data.field;
                sdata.ATTACHMENT = uploadfiles;
                var sendData = {};
                sendData.DATA = JSON.stringify(sdata);

                layer.msg('确认保存楼宇吗', {
                    time: 0
                    , btn: ['确定', '取消']
                    , shade: 0.3
                    , yes: function (index) {
                        layer.close(index); // 关闭当前提示框
                        $.ajax({
                            url: "/building/editBuilding",
                            data: sendData,
                            dataType: "json",
                            type: "post",
                            async: false,
                            success: function (res) {
                                if (res.errcode === "0") {
                                    var i = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(i);  // 关闭修改楼宇页面
                                    parent.reload();    // 父页面表格刷新
                                    parent.layer.msg("修改成功", {offset: '150px'});   // 父页面弹出修改成功
                                } else if (res.errcode === "1") {
                                    layer.msg(res.errmsg, function () {
                                    });
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                console.error(XMLHttpRequest.status);
                                console.error(XMLHttpRequest.readyState);
                                console.error(textStatus);
                            }
                        });
                    }
                });
            }
            return false;
        });
    });

    /* 新建单元 */
    function createUnit() {
        layer.prompt({title: '请输入单元号，并确认', maxlength: 3}, function (text, index) {
            var regu = /^[1-9]\d*$/;    // 正整数
            if (!regu.test(text)) {
                layer.tips('单元必须为正整数', '.layui-layer-input', {
                    tips: 1
                });
            } else {
                var flag = true;
                $(".unit-list").find(".unit-list-res").each(function (index, elem) {
                    if ($(this).data("deleted") != 1 && $(this).data("name") == text) {
                        flag = false;
                        return false;
                    }
                });
                if (flag === false) {
                    layer.tips('单元已存在', '.layui-layer-input', {
                        tips: 1
                    });
                } else {
                    var str = '<div class="layui-input-block unit-list-res" data-id="" data-name="' + text + '" data-open="on" data-deleted="0">          <div class="layui-form-mid layui-word-aux">' + text + ' 单元</div>\n' +
                        '      <div class="layui-input-inline layui-input-inline50">\n' +
                        '          <input type="checkbox" checked="" name="UNIT_IS_OPEN" data-unitid="" lay-skin="switch" lay-filter="switchUnit" lay-text="启用|关闭">\n' +
                        '      </div>\n' +
                        '      <a class="layui-btn layui-btn-primary layui-btn-mini" href="javascript:;" onclick="deleteUnit(this);"><i class="layui-icon"></i> 删除</a></div>';
                    $(".unit-list").append(str);
                    form.render();
                    layer.close(index);
                }
            }
        });
    }

    /* 新建楼层 */
    function createFloor() {
        layer.prompt({title: '请输入楼层，并确认', maxlength: 3}, function (text, index) {
            var regu = /^-?\d+$/;
            if (!regu.test(text) || text == 0) {
                layer.tips('楼层必须为非零整数', '.layui-layer-input', {
                    tips: 1
                });
            } else {
                var flag = true;
                $(".floor-list").each(function () {
                    if (!$(this).is(":hidden")){
                        $(this).find(".floor-list-res").each(function (index, elem) {
                            if ($(this).data("deleted") != 1 && $(this).data("name") == text) {
                                flag = false;
                                return false;
                            }
                        });
                    }
                });
                if (flag === false) {
                    layer.tips('楼层已存在', '.layui-layer-input', {
                        tips: 1
                    });
                } else {
                    var str = '<div class="layui-input-block floor-list-res" data-id="" data-name="' + text + '" data-open="on" data-deleted="0">          <div class="layui-form-mid layui-word-aux">' + text + ' 层</div>\n' +
                        '      <div class="layui-input-inline layui-input-inline50">\n' +
                        '          <input type="checkbox" checked="" name="FLOOR_IS_OPEN" data-unitid="" lay-skin="switch" lay-filter="switchFloor" lay-text="启用|关闭">\n' +
                        '      </div>\n' +
                        '      <a class="layui-btn layui-btn-primary layui-btn-mini" href="javascript:;" onclick="deleteFloor(this);"><i class="layui-icon"></i> 删除</a></div>';
                    $(".floor-list").each(function () {
                        if (!$(this).is(":hidden")){
                            $(this).append(str);
                        }
                    });

                    form.render();
                    layer.close(index);
                }
            }
        });
    }

    function deleteUnit(obj, id) {
        $(obj).parent().attr("data-deleted", "1");
        $(obj).parent().hide();
    }

    function deleteFloor(obj, id) {
        $(obj).parent().attr("data-deleted", "1");
        $(obj).parent().hide();
    }

    var operate = {
        deleteImg: function (obj, id) {
            $(obj).parent().parent().remove();
            for (var i = 0; i < uploadfiles.length; i++) {
                if (uploadfiles[i].id == id) {
                    uploadfiles.splice(i, 1);
                }
            }
        }
    }

</script>
</body>

</html>